package sk.openit.xml.stax.cursor;

import java.io.FileWriter;
import java.io.IOException;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import sk.openit.xml.entity.DbConfig;
import sk.openit.xml.entity.DbConfigTags;

import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;

public class DbConfigWriter implements DbConfigTags {
	private String fileName;

	public DbConfigWriter(String fileName) {
		this.fileName = fileName;
	}

	public void serialize(DbConfig dbConfig) {
		XMLOutputFactory xof = XMLOutputFactory.newInstance();
		XMLStreamWriter xtw = null;
		try {
			xtw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(new FileWriter(fileName)));
			xtw.writeStartDocument("utf-8", "1.0");
			xtw.writeStartElement(CONFIG);
			xtw.writeAttribute(DB_TYPE, dbConfig.getDbType());
			xtw.writeStartElement(HOST);
			xtw.writeCharacters(dbConfig.getHost());
			xtw.writeEndElement();
			xtw.writeStartElement(HOST);
			xtw.writeCharacters(dbConfig.getHost());
			xtw.writeEndElement();
			xtw.writeStartElement(PORT);
			xtw.writeCharacters(dbConfig.getPort());
			xtw.writeEndElement();
			xtw.writeStartElement(INSTANCE);
			xtw.writeCharacters(dbConfig.getInstance());
			xtw.writeEndElement();
			xtw.writeStartElement(DATABASE);
			xtw.writeCharacters(dbConfig.getDatabase());
			xtw.writeEndElement();
			xtw.writeStartElement(USER);
			xtw.writeCharacters(dbConfig.getUser());
			xtw.writeEndElement();
			xtw.writeEndDocument();
			xtw.flush();
			xtw.close();
		} catch (XMLStreamException e) {
			System.err.println("Unable to process XML stream");
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Unable to save file: " + fileName);
			e.printStackTrace();
		}
	}
}
